import {Component} from '@angular/core';
import {IonicModule} from '@ionic/angular';
import { NgIf } from '@angular/common';
import { OCR, OCRSourceType,OCRResult } from '@ionic-native/ocr/ngx';

@Component({
  selector: 'ocr',
  templateUrl: 'ocr.page.html',
  styleUrls: ['ocr.scss'],
  standalone: true,
  imports: [IonicModule,NgIf],
})
export class OCRPage {
  extractedText: string;
  imgSrc: string;
  imageUri: string;

  constructor(private ocr: OCR) {
    this.extractedText=""
    this.imgSrc=""
    this.imageUri=""

  }

  extractText() {
   
    const regex = /^data:image\/[a-z]+;base64,/;
    let result = this.imgSrc.replace(regex, '');
    console.log('>>>>>>>>>>>>>>>>>result',result)
    console.log(">>>>>>>>>>>>>>this.imgSrc",this.imgSrc)
   this.ocr.recText(OCRSourceType.BASE64 ,result).then(
      (res: OCRResult) =>{
        console.log('>>>>>>>>>>>>OCRResult',res.blocks)
        this.extractedText = res.blocks.blocktext.toString()
      },
      (error: any) => {
        console.log('>>>>>>>>>>>>error',error)
      }
    );
  }

  onChange(event: any): void {
    if (event.target.files.length === 0) {
      return;
    }

    const file = event.target.files[0];
    const reader = new FileReader();

    reader.onloadend = () => {
      if(reader.result){
        this.imgSrc = reader.result.toString();

      }
    };

    reader.readAsDataURL(file);
  }
}
